package com.appspot.yusupova;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.yusupova.verses.CachedVerseMap;
import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

/**
 * This servlet receives an XMPP message as HTTP request and returns 
 * another XMPP messages which contains the most suitable verse for 
 * the original message. 
 * 
 * @author Rouslan Shchoutchinov.
 */
@SuppressWarnings("serial")
public final class XMPPServlet extends HttpServlet {

    private static final Logger logger = Logger.getLogger(XMPPServlet.class.getName());

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doPost(req, resp);
    }
    
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            String strStatus = "";
            XMPPService xmpp = XMPPServiceFactory.getXMPPService();
            
            Message msg = xmpp.parseMessage(req);
            JID fromJid = msg.getFromJid();
            String body = msg.getBody();
            logger.info("Received a message from " + fromJid + " and body = " + body);
            
            String msgBody;
            try {
                msgBody = "\r\n" + CachedVerseMap.get(body);
            } catch (RuntimeException re) {
                msgBody = "Cannot find verse with text: " + body;
                re.printStackTrace();
                logger.log(Level.SEVERE, "Error during getting verse", re);
            }
            Message replyMessage = new MessageBuilder().withRecipientJids(fromJid).withBody(msgBody).build();
            
            if (xmpp.getPresence(fromJid).isAvailable()) {
                SendResponse status = xmpp.sendMessage(replyMessage);
                boolean messageSent = (status.getStatusMap().get(fromJid) == SendResponse.Status.SUCCESS);
                if (messageSent) {
                    strStatus = "Message has been sent successfully";
                } else {
                    strStatus = "Message could not be sent";
                }
                logger.info(strStatus);
            }
            
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

}
